from datetime import timedelta
from django.http import JsonResponse
from django.shortcuts import redirect, render, HttpResponse
from django.views.decorators.http import require_http_methods
from django.utils import timezone
from web import models
from web.forms.account import LoginFormWithCode, LoginFormWithPW, RegisterModelForm, SendSmsForm
import json


# Create your views here.
@require_http_methods(['GET'])
def index(request):
    '''
    session记录
    ID
    plan
    '''
    mode = request.GET.get('mode', 'login')
    prompt = '还没有账号？'
    submitLabel = '登录'
    quick = False
    link = {
        'to': '/account?mode=register',
        'label': '去注册'
    }
    if mode == 'quick':
        form = LoginFormWithCode(request)
        quick = True
    elif mode == 'register':
        form = RegisterModelForm(request)
        prompt = '已有账号？'
        submitLabel = '注册'
        link = {
            'to': '/account',
            'label': '去登录'
        }
    else:
        form = LoginFormWithPW(request)
    return render(request,'web/account.html',{
        'mode': mode,
        'submitLabel': submitLabel,
        'prompt': prompt,
        'form': form,
        'link': link,
        'quick': quick
    })

@require_http_methods(['GET', 'POST'])
def process(request):
    if request.method == 'GET':
        mode = request.GET.get('mode')
        if mode == 'quick':
            form = LoginFormWithCode(request, data=request.GET)
        else:
            form = LoginFormWithPW(request, data=request.GET)
        if not form.is_valid():
            return JsonResponse({'status': False, 'error': form.errors})
        if not mode == 'quick':
            mobile_phone = form.cleaned_data['mobile_phone']
            password = form.cleaned_data['password']
            exists = models.User.objects.filter(mobile_phone=mobile_phone, password=password).exists()
            if not exists:
                return JsonResponse({'status': False, 'msg': '密码错误'})
        user = models.User.objects.get(mobile_phone=form.cleaned_data['mobile_phone'])
        # session 存储ID, plan
        request.session['ID'] = user.ID
        # 查找plan, 按plan等级，降序，获取有效的
        transaction = models.Transaction.objects.order_by("-plan").filter(user_ID=user.ID, unvalid_time__gte=timezone.now()).first()
        request.session['plan'] = transaction.plan
        # 设置有效期
        request.session.set_expiry(10 * 60)
        response = JsonResponse({'status': True, 'next': '/home'})
        # 设置cookie
        response.set_signed_cookie('uid', user.ID, 'zrgj', max_age=10 * 60)
        return response
    else:
        form = RegisterModelForm(request, data=request.POST)
        if form.is_valid():
            userInfo = form.cleaned_data
            exists = models.User.objects.filter(mobile_phone=userInfo['mobile_phone']).exists()
            if exists:
                return JsonResponse({'status': False, 'msg': '该手机号已被注册！'})
            # 新建用户
            user = models.User()
            user.username = userInfo['username']
            user.password = userInfo['password']
            user.email = userInfo['email']
            user.mobile_phone = userInfo['mobile_phone']
            user.save()
            # 生成免费版套餐
            duration = models.Plans.objects.get(plan=1).valid_duration
            duration = 365 if duration == '1y' else (365)*80
            models.Transaction.objects.create(user_ID=user.ID, deal_time=timezone.now(), plan=1, unvalid_time=(timezone.now() + timedelta(duration)))
            return JsonResponse({'status': True})
        else:
            return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):

    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})

def logout(request):
    request.session.clear()
    response = JsonResponse({'status': True})
    response.delete_cookie('uid')
    return response